package com.csw.shuanfa.CodeImprove.exercise.future;

import com.csw.shuanfa.utils.ThreadPoolUtil;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class CompletableFuture_WhenComplete_Exceptionally {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = ThreadPoolUtil.getExecutorServiceCPU();
        try {
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                }
                if (new Random().nextInt(10) % 2 == 0) {
                    int i = 12 / 0;
                }
                System.out.println("执行结束！");
                return "test";
            }, threadPool);

            future.whenComplete(new BiConsumer<String, Throwable>() {
                @Override
                public void accept(String t, Throwable action) {
                    System.out.println(t + " 执行完成！");
                }
            });

            future.exceptionally(new Function<Throwable, String>() {
                @Override
                public String apply(Throwable t) {
                    System.out.println("执行失败：" + t);
                    return "异常xxxx";
                }
            }).join();
        } catch (Exception e) {
            threadPool.shutdown();
            throw new RuntimeException(e);
        }


    }
}